<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:" v-if="isBatchStock">
                        <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                    </el-form-item>
                    <el-form-item label="组合编码:" v-if="isBatchStock">
                        <el-select v-model="instruction.fundAccountCode" size="mini">
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="合约代码:" v-if="isBatchFund">
                        <el-select
                            v-model="instruction.stockCode"
                            filterable
                            :filter-method="getStockCodeList"
                            :loading="selectLoading"
                            @change="handleStockCodeChange"
                            @visible-change="handleStockVisibleChange"
                            size="mini"
                            clearable
                            @clear="getStockCodeList('')"
                        >
                            <el-option
                                v-for="i in stockCodeSelectData"
                                :key="i.stockCode"
                                :label="i.stockCode + ' ' + i.stockNameSt"
                                :value="i.stockCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务类型:">
                        <el-select v-model="instruction.businClass" size="mini">
                            <el-option v-for="i in businessTypeData" :key="i.value" :label="i.label" :value="i.value"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="委托方向:">
                        <el-select v-model="instruction.orderDirection" size="mini" :class="['font-color-' + textColor]">
                            <el-option
                                v-for="i in orderDirectionSelectData"
                                :key="i.dictKey"
                                :label="i.dictKeyName"
                                :value="i.dictKey"
                                :style="handleTextColor(i.dictKey)"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="投资类型:" v-if="isBatchFund">
                        <el-select v-model="instruction.investType" size="mini">
                            <el-option v-for="i in investmentTypeData" :key="i.value" :label="i.label" :value="i.value"> </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="投资类型:" v-if="isBatchStock">
                        <el-select v-model="instruction.investType" size="mini">
                            <el-option v-for="i in investmentTypeData" :key="i.value" :label="i.label" :value="i.value"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="指令价格:">
                        <RiskInputNumber
                            :input="instruction.orderPrice"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="3"
                            :maxlength="15"
                            :field="'orderPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="指令数量:">
                        <RiskInputNumber
                            :input="instruction.orderAmount"
                            :inputAfter="'手'"
                            :colorStyle="textColor"
                            :maxlength="15"
                            :precision="2"
                            :field="'orderAmount'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="合约价值:">
                        <RiskInputNumber
                            :input="orderBalances"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :maxlength="15"
                            :field="'orderBalances'"
                            :disabled="true"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts">
import Invest from '@/common/dict/invest';
import { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { highlightColor, handleTextColor } from '@/utils/tools';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { SelectOptionItemData } from '@/pages/risk-time/types/SelectOptionItemData';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import { getBusinessType, getFutureContractMulti } from '@/pages/risk-time/api';

@Component({
    name: 'FutureGoodsForm',
    components: {
        RiskInputNumber,
        RiskEntryInput,
    },
})

// 期货指令
export default class FutureGoodsForm extends Vue {
    @Prop()
    detail: any;
    @Prop()
    selectStockInfo: any;
    @Prop()
    isBatchFund: boolean; // 多基金指令
    @Prop()
    isBatchStock: boolean; // 多基金指令

    Invest: any = new Invest();
    handleTextColor = handleTextColor;
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    allStockType: any[] = [];
    allOrderDirection: any[] = [];
    orderDirectionSelectData: any[] = []; // 订单方向下拉框数据
    investTypeSelectData: any[] = []; // 投资类型下拉框数据
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    contractMulti: string = ''; // 合约乘数
    stockReport: any[] = [];
    textColor: string = ''; // 红绿凸显

    instruction = {
        fundCode: '', // 产品代码
        fundAccountCode: '', // 组合编码
        reportCode: '', // 申报代码
        marketCode: '',
        orderDirection: '', // 委托方向
        businClass: '4',
        orderPrice: '', // 指令价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 合约价值
        orderBalances: '', // 展示合约价值
        investType: 'b', // 投资类型
        fundNameSt: '',
        fundAccountName: '',
        stockCode: '',
    };
    orderBalances: string = ''; // 展示合约价值
    businessTypeData: SelectOptionItemData[] = [];
    // 业务类型
    defaultBusinessTypeData: SelectOptionItemData[] = [
        {
            label: '期货业务',
            value: '4',
        },
    ];

    // 投资类型
    private investmentTypeData = [
        {
            label: '投机',
            value: 'a',
        },
        {
            label: '套保',
            value: 'b',
        },
        {
            label: '套利',
            value: 'c',
        },
    ];
    stockInfo: any = {};

    async mounted() {
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取投资类型下拉框数据
        this.investTypeSelectData = objToArr(this.Invest.investType);
        // 获取证券代码下拉框数据
        this.getStockCodeList('');
        // 获取所有证券类别 (用于筛选订单方向)
        this.allStockType = await SGU_CACHE('StockType', '/dict/stockType/list', []);
        // 获取所有订单方向
        this.allOrderDirection = await SGU_CACHE('TradeDirection', '/dict/tradeDirections', []);
        this.businessTypeData = this.defaultBusinessTypeData;
    }

    @Watch('instruction', { immediate: true, deep: true })
    setValues() {
        this.$emit('handleSettingValue', this.instruction, '7');
    }

    @Watch('selectStockInfo', { immediate: true, deep: true })
    onWatchStockInfo() {
        if (this.selectStockInfo) {
            this.stockInfo = this.selectStockInfo;
            this.instruction.stockCode = this.selectStockInfo?.stockCode;
        }
        this.handleStockCodeChange(this.instruction.stockCode);
    }

    @Watch('detail', { immediate: true, deep: true })
    async onWatchDetail() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction: any = {};
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            await this.getStockCodeList(instruction.stockCode);
            this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === instruction.stockCode);
            if (this.stockInfo && this.stockInfo.marketCode && this.stockInfo.stockType) {
                this.handleStockBusinessType(this.stockInfo.marketCode, this.stockInfo.stockType, false);
            }
            await this.getContractMulti(this.stockInfo?.stockCode);
            this.instruction = JSON.parse(JSON.stringify(instruction));
            this.instruction.businClass = instruction.businessType;
            this.getCalOrderBalance();
        }
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        if (newData && newData.length) {
            this.instruction.fundAccountCode = newData[0].fundAccountCode;
        }
    }

    /**
     * 判断字段颜色
     */
    @Watch('instruction', { immediate: true, deep: true })
    handleFieldColor() {
        if (['X', 'V'].includes(this.instruction.orderDirection)) {
            this.textColor = highlightColor()[1];
        } else if (['Y', 'W'].includes(this.instruction.orderDirection)) {
            this.textColor = highlightColor()[2];
        } else {
            this.textColor = highlightColor()[0];
        }
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        if (field == 'orderBalances') {
            this[field] = value;
            this.instruction.orderBalances = value;
        } else {
            this.instruction[field] = value;
        }
        if (field === 'orderPrice' || field === 'orderAmount') {
            this.getCalOrderBalance();
        }
    }

    get computedFundAccountCodeSelectData(): any {
        return this.fundAccountCodeSelectData[this.instruction.fundCode];
    }

    // 计算合约价值
    getCalOrderBalance() {
        this.orderBalances = (
            Number(this.instruction.orderPrice || 0) *
            Number(this.instruction.orderAmount || 0) *
            Number(this.contractMulti || 0)
        ).toString();
        this.instruction.orderBalances = this.orderBalances;
        this.instruction.orderBalance = (Number(this.instruction.orderPrice || 0) * Number(this.instruction.orderAmount || 0)).toString();
    }

    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        this.handleFundCodeChange(val);
    }

    handleFundCodeChange(value: string) {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === value) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    handleFundAccountCodeChange(value: string) {
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || []).find(item => item.fundAccountCode === value) || {};
        this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    // 获取证券代码下拉框数据
    async getStockCodeList(val: string) {
        this.selectLoading = true;
        await this.$axios
            .post('/dict/stock/report/select/' + 2 + '/v1', {
                dictKey: val,
                dictKeyName: val,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res || [];
                this.selectLoading = false;
            });
    }

    handleStockCodeChange(value: string): void {
        this.instruction.orderDirection = '';
        if (value) {
            this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === value);
            // this.orderDirectionSelectData = this.stockInfo?.tradeDirections;
            this.instruction.reportCode = this.stockInfo?.reportCode;
            this.instruction.marketCode = this.stockInfo?.marketCode;
            this.$emit('getStockInfo', this.stockInfo);
            this.getContractMulti(this.stockInfo?.stockCode);

            if (this.stockInfo.marketCode && this.stockInfo.stockType) {
                this.handleStockBusinessType(this.stockInfo.marketCode, this.stockInfo.stockType, true);
            }
        } else {
            this.instruction.reportCode = '';
            this.orderDirectionSelectData = [];
        }
        this.instruction.orderAmount = '';
        this.instruction.orderPrice = '';
        this.instruction.orderBalance = '';
        this.orderBalances = '';
        this.instruction.orderBalances = this.orderBalances;
    }

    handleStockVisibleChange(val) {
        if (!val) {
            this.getStockCodeList(this.instruction.stockCode);
        }
    }

    /**
     * reset: 是否设置委托方向为默认第一个
     */
    async handleStockBusinessType(marketCode, stockType, reset) {
        let res = await getBusinessType(marketCode, stockType);
        if (res && res.length > 0) {
            this.businessTypeData = res.map(
                item =>
                    ({
                        label: item.dictKeyName,
                        value: item.dictKey,
                    } as SelectOptionItemData)
            );
            let innerOrderDirectionData = res;
            innerOrderDirectionData.filter(ele => {
                if (ele.dictKey == this.instruction.businClass) {
                    if (ele['innerDictionary'] && JSON.stringify(ele['innerDictionary']) !== '{}') {
                        this.orderDirectionSelectData = JSON.parse(ele['innerDictionary'] || '[]');
                    } else {
                        this.orderDirectionSelectData = [];
                        this.instruction.orderDirection = '';
                    }
                    if (this.orderDirectionSelectData.length && reset) {
                        this.instruction.orderDirection = this.orderDirectionSelectData[0].dictKey;
                    } else {
                        if (reset) {
                            this.yh_message_warn('该业务类型无对应的委托方向');
                        }
                    }
                }
            });
        } else {
            this.businessTypeData = this.defaultBusinessTypeData;
        }
    }

    /**
     * 获取合约乘数
     */
    async getContractMulti(stockCode) {
        if (stockCode) {
            let contractMulti = await getFutureContractMulti(stockCode);
            if (!contractMulti) {
                contractMulti = 0;
            } else {
                this.contractMulti = contractMulti;
            }
            this.$emit('getContractMulti', this.contractMulti);
        }
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-measure/style/measure';
@import '@/pages/risk-time/styles/order-form';
</style>
